import React, { useState, useEffect, useRef, useCallback } from 'react'
import { ChatInterface } from '@/components/ChatInterface'
import { ConversationList } from '@/components/ConversationList'
import { ChatService } from '@/services/chatService'
import { ChatMessage } from '@/services/chatService'

export function ChatAppWithSidebar() {
  const [messages, setMessages] = useState<ChatMessage[]>([])
  const [inputMessage, setInputMessage] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [conversationId, setConversationId] = useState<string>()
  const [userId] = useState<number>(1) // 默认用户ID，实际应用中应该从认证系统获取
  const [isAgentMode, setIsAgentMode] = useState(false)
  const conversationListRef = useRef<{ addOrUpdateConversation: (id: string, msg: string) => void }>(null)

  const chatService = ChatService.getInstance()

  // 加载对话历史（如果有conversationId）
  useEffect(() => {
    if (conversationId && conversationId !== 'unknown') {
      loadConversationHistory()
    }
  }, [conversationId])

  const loadConversationHistory = async () => {
    if (!conversationId || conversationId === 'unknown') return
    
    try {
      const history = await chatService.getConversationHistoryFromDB(parseInt(conversationId))
      const chatMessages: ChatMessage[] = history.map(msg => ({
        id: msg.id.toString(),
        content: msg.content,
        role: msg.role as 'user' | 'assistant',
        timestamp: new Date(msg.created_at)
      }))
      setMessages(chatMessages)
    } catch (error) {
      console.error('Error loading conversation history:', error)
    }
  }

  const handleSendMessage = async () => {
    if (!inputMessage.trim() || isLoading) return

    const userMessage: ChatMessage = {
      id: Date.now().toString(),
      content: inputMessage,
      role: 'user',
      timestamp: new Date()
    }

    setMessages(prev => [...prev, userMessage])
    const currentMessage = inputMessage
    setInputMessage('')
    setIsLoading(true)

    try {
      // 根据模式选择不同的API
      const { stream, conversationId: newConversationId } = isAgentMode 
        ? await chatService.sendAgentMessage(currentMessage, conversationId, userId.toString())
        : await chatService.sendMessageWithMemory(currentMessage, conversationId, userId.toString())
      
      // 更新conversationId（如果是新对话）
      if (!conversationId && newConversationId !== 'unknown') {
        setConversationId(newConversationId)
      }
      
      let assistantContent = ''
      let messageId = Date.now().toString()
      let updateTimeout: number | null = null

      // 先创建一个空的assistant消息，然后逐步更新内容
      const assistantMessage: ChatMessage = {
        id: messageId,
        content: '',
        role: 'assistant',
        timestamp: new Date(),
        isStreaming: true
      }
      
      setMessages(prev => [...prev, assistantMessage])

      // 批量更新函数，减少频繁的状态更新
      const updateMessage = (content: string, streaming: boolean = true) => {
        setMessages(prev => {
          return prev.map(msg => 
            msg.id === messageId 
              ? { ...msg, content, isStreaming: streaming }
              : msg
          )
        })
      }

      for await (const chunk of stream) {
        // 直接处理文本内容
        assistantContent += chunk
        
        // 清除之前的更新定时器
        if (updateTimeout) {
          clearTimeout(updateTimeout)
        }
        
        // 设置新的更新定时器，减少频繁更新
        updateTimeout = setTimeout(() => {
          updateMessage(assistantContent, true)
        }, 16) // 约60fps的更新频率
      }
      
      // 清除最后的定时器并立即更新
      if (updateTimeout) {
        clearTimeout(updateTimeout)
      }
      updateMessage(assistantContent, true)
      
      // 流式传输完成，移除 isStreaming 标志
      setMessages(prev => 
        prev.map(msg => 
          msg.id === messageId 
            ? { ...msg, isStreaming: false }
            : msg
        )
      )

      // 更新对话列表
      const finalConversationId = newConversationId !== 'unknown' ? newConversationId : conversationId
      if (finalConversationId) {
        updateConversationInList(finalConversationId, currentMessage)
      }
      
    } catch (error) {
      console.error('Error sending message:', error)
      // 移除loading状态的消息
      setMessages(prev => prev.slice(0, -1))
    } finally {
      setIsLoading(false)
    }
  }

  const updateConversationInList = (convId: string, lastMessage: string) => {
    // 直接更新对话列表，而不是重新加载
    const updateEvent = new CustomEvent('updateConversation', {
      detail: { conversationId: convId, lastMessage, timestamp: new Date() }
    })
    window.dispatchEvent(updateEvent)
  }

  const handleSelectConversation = (selectedConversationId: string, chatMode?: string) => {
    if (selectedConversationId !== conversationId) {
      setConversationId(selectedConversationId)
      setMessages([]) // 清空当前消息，将通过useEffect加载新的历史记录
      
      // 根据对话模式自动切换智能体模式
      if (chatMode === 'agent') {
        setIsAgentMode(true)
      } else {
        setIsAgentMode(false)
      }
    }
  }

  const handleNewConversation = () => {
    setConversationId(undefined)
    setMessages([])
    setInputMessage('')
  }

  const handleToggleAgentMode = (enabled: boolean) => {
    setIsAgentMode(enabled)
    // 可以选择在切换模式时清空对话历史
    // setMessages([])
    // setConversationId(undefined)
  }

  return (
    <div className="h-screen flex bg-background">
      {/* 对话列表侧边栏 */}
      <div className="w-80 border-r border-border flex-shrink-0 flex">
        <ConversationList
          currentConversationId={conversationId}
          onSelectConversation={handleSelectConversation}
          onNewConversation={handleNewConversation}
          userId={userId}
        />
      </div>
      
      {/* 聊天界面 */}
      <div className="flex-1 min-w-0">
        <ChatInterface
          messages={messages}
          inputMessage={inputMessage}
          setInputMessage={setInputMessage}
          onSendMessage={handleSendMessage}
          isLoading={isLoading}
          conversationId={conversationId}
          isAgentMode={isAgentMode}
          onToggleAgentMode={handleToggleAgentMode}
        />
      </div>
    </div>
  )
}